﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Linq.SqlClient;
using S9Engine;


public partial class Customer : Parser
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            InitAll();

            if (!CheckLogin()) Response.Redirect("login.aspx");

            _parser.SetCurrentDir("~/html");
            _parser.SetLanguageFile("~/templates/language.txt", _currentLanguage);

            Session["CurrentPage"] = "Customer.aspx";

            if ((Session["UserType"] == null) || (Session["UserType"] as string != "Administrator"))
            {
                LoadFile("customer.html", false);
                _parser.Parse("Main.NoneAdmin");
            }
            else
            {
                string type = Request["type"] ?? "default";

                _DR.Refresh(System.Data.Objects.RefreshMode.StoreWins, _DR.Users);

                switch (type)
                {
                    case "default":
                        {
                            LoadFile("customer.html", false);
                            LoadCustomers();
                            break;
                        }
                    case "add":
                        {
                            LoadFile("customer_add.html", false);
                            LoadCustomerByID(null);
                            break;
                        }
                    case "edit":
                        {
                            if (Request["id"] == null)
                            {
                                Response.Redirect("customer.aspx");
                            }
                            else
                            {
                                LoadFile("customer_add.html", false);
                                LoadCustomerByID(long.Parse(Request["id"]));
                            }
                            break;
                        }
                    case "delete":
                        {
                            if (Request["id"] == null)
                            {
                                Response.Redirect("customer.aspx");
                            }
                            else
                            {
                                DeleteCustomerByID(long.Parse(Request["id"]));
                            }
                            break;
                        }
                    default: goto case "default";
                }
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
        finally
        {
            _parser.Parse("Main");
            _parser.Out("Main");
        }
    }

    private void LoadCustomers()
    {
        try
        {
            var customerMeta = _DR.Meta.Where(m => m.Type.Equals("User")).Select(m => new
            {
                ID = m.ID,
                Key = m.Key,
                Value = m.Value
            });

            var customers = _DR.Users.Where(u => u.Type.Equals("Customer")).Select(u => new
            {
                ID = u.ID,
                Username = u.Username,
                Fullname = u.Fullname,
                Password = u.Password
            }).ToList();

            string search = Request["search"] ?? string.Empty;

            if (!string.IsNullOrEmpty(search))
            {
                customers = customers.Where(c => c.Fullname.Contains(search) || c.Username.Contains(search)).Select(u => new
                {
                    ID = u.ID,
                    Username = u.Username,
                    Fullname = u.Fullname,
                    Password = u.Password
                }).ToList();

                _parser.Assign("searchValue", search);
            }

            double totalRecord = customers.Count();
            int page = int.Parse(Request["page"] ?? "1");
            int pageSize = _rowsPerPage;
            int totalPage = (int)(totalRecord / pageSize);
            
            if (totalPage * pageSize < totalRecord) totalPage++;

            if (totalRecord != 0)
            {
                int startRecord = (page == 1 ? 0 : ((page - 1) * pageSize));
                int endRecord = (int)(page * pageSize > totalRecord ? totalRecord : page * pageSize);

                for (int i = startRecord; i < endRecord; i++)
                {
                    _parser.Assign("customerID", customers[i].ID.ToString());
                    _parser.Assign("customerName", customers[i].Fullname);
                    _parser.Assign("customerEmail", customers[i].Username);
                    _parser.Parse("Main.Content.Table.TableItem");
                }

                _parser.Assign("totalPage", totalPage.ToString());
                _parser.Assign("totalRecord", totalRecord.ToString());
                _parser.Assign("currentPage", page.ToString());

                if (totalPage != 1)
                {
                    int pagingPage = page / _pageRange;
                    int startPage = 1;
                    int endPage = 1;

                    if (page % _pageRange == (_pageRange - 1) && page > _pageRange)
                    {
                        startPage = page;
                    }
                    else
                    {
                        startPage = (pagingPage * _pageRange == 0 ? 1 : pagingPage * _pageRange);
                    }

                    endPage = (startPage + (_pageRange - 1) > totalPage ? totalPage : startPage + (_pageRange - 1));

                    _parser.Assign("pageIndexPrevious", (page == 1 ? 1 : page - 1).ToString());
                    _parser.Assign("pageIndexNext", (page == totalPage ? totalPage : page + 1).ToString());


                    for (int i = startPage; i <= endPage; i++)
                    {
                        _parser.Assign("currentPageStyle", page == i ? " class=\"current\"" : string.Empty);

                        if (!string.IsNullOrEmpty(search)) _parser.Assign("searchInfo", string.Format("&search={0}", search));

                        _parser.Assign("pageIndex", i.ToString());
                        _parser.Parse("Main.Content.Table.Paging.PagingItem");
                    }

                    _parser.Parse("Main.Content.Table.Paging.PagingPrevious");
                    _parser.Parse("Main.Content.Table.Paging.PagingNext");
                }

                _parser.Parse("Main.Content.Table.Paging");
                _parser.Parse("Main.Content.Table");
            }
            
            _parser.Parse("Main.Content");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void LoadCustomerByID(long? ID)
    {
        try
        {
            if (ID == null) //AddNew
            {
                _parser.Assign("customerName", string.Empty);
                _parser.Assign("password", string.Empty);
                _parser.Assign("customerFullName", string.Empty);

                _parser.Parse("Main.Content.EditForm.AddNew");
                _parser.Parse("Main.Content.EditForm");
                _parser.Parse("Main.AddNewCustomer");
            }
            else //Edit
            {
                Users customer = _DR.Users.Where(t => t.ID.Equals(ID.Value)).FirstOrDefault();
                var customerMeta = _DR.Meta.Where(m => m.Object.Equals(ID.Value) && m.Type.Equals("Customer")).ToList();

                if (customer == null)
                {
                    _parser.Parse("Main.Content.Error");
                }
                else
                {
                    string year = customerMeta.Where(c => c.Key.Equals("Year")).Select(c => c.Value).FirstOrDefault() ?? string.Empty;
                    string month = customerMeta.Where(c => c.Key.Equals("Month")).Select(c => c.Value).FirstOrDefault() ?? string.Empty;
                    string day = customerMeta.Where(c => c.Key.Equals("Day")).Select(c => c.Value).FirstOrDefault() ?? string.Empty;

                    _parser.Assign("customerID", customer.ID.ToString());
                    _parser.Assign("customerEmail", customer.Username);
                    _parser.Assign("customerFirstName", customerMeta.Where(c => c.Key.Equals("FirstName")).Select(c => c.Value).FirstOrDefault() ?? string.Empty);
                    _parser.Assign("customerLastName", customerMeta.Where(c => c.Key.Equals("LastName")).Select(c => c.Value).FirstOrDefault() ?? string.Empty);
                    _parser.Assign("customerOldPassword", string.Empty);
                    _parser.Assign("customerNewPassword", string.Empty);
                    _parser.Assign("customerConfirmPassword", string.Empty);
                    _parser.Assign("customerDOB", month + "/" + day + "/" + year);
                    _parser.Assign("customerAddress", customerMeta.Where(c => c.Key.Equals("Address")).Select(c => c.Value).FirstOrDefault() ?? string.Empty);
                    _parser.Assign("customerCity", customerMeta.Where(c => c.Key.Equals("City")).Select(c => c.Value).FirstOrDefault() ?? string.Empty);
                    _parser.Assign("customerPostalCode", customerMeta.Where(c => c.Key.Equals("PostalCode")).Select(c => c.Value).FirstOrDefault() ?? string.Empty);

                    _parser.Parse("Main.Content.EditForm.Edit");
                    _parser.Parse("Main.Content.EditForm.ConfirmPassword");
                    _parser.Parse("Main.Content.EditForm");
                    _parser.Parse("Main.EditCustomer");
                }
            }
            
            _parser.Parse("Main.Content");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteCustomerByID(long ID)
    {
        try
        {
            Users customer = _DR.Users.Where(u => u.ID.Equals(ID)).FirstOrDefault();

            if (customer != null)
            {
                _DR.DeleteObject(customer);
                _DR.SaveChanges();
            }

            Response.Redirect("customer.aspx");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }
}